package com.ccf.business.source.listener;

import cn.hutool.core.util.StrUtil;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUpload;
import org.apache.commons.fileupload.FileUploadBase;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.springframework.web.multipart.MaxUploadSizeExceededException;
import org.springframework.web.multipart.MultipartException;
import org.springframework.web.multipart.commons.CommonsMultipartResolver;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * 描述：
 *  上传文件的解析器
 * @author xianggj
 * @Date 2022/2/16 16:31
 **/
public class MultipartListenerResolver extends CommonsMultipartResolver {

    /**
     * 进度
     */
    public static final Map<String, Double> FILE_PROGRESS_MAP = new ConcurrentHashMap<>();

    public static final Double FAIL_DOUBLE = -1.0;

    public static final String FILE_HEADER = "Content-Disposition";

    public static final String FILE_NAME = ";filename=";

    @Override
    protected MultipartParsingResult parseRequest(HttpServletRequest request) throws MultipartException {
        String encoding = determineEncoding(request);
        FileUpload fileUpload = prepareFileUpload(encoding);
        HttpSession session = request.getSession();
        String fileName = request.getHeader(FILE_HEADER);
        try {
            fileName =
                    URLDecoder.decode(StrUtil.subAfter(fileName, FILE_NAME, true), "UTF-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
            if (fileName != null){
                FILE_PROGRESS_MAP.put(fileName, FAIL_DOUBLE);
            }
            throw new MaxUploadSizeExceededException(fileUpload.getSizeMax(), e);
        }
        //设置监听器
        fileUpload.setProgressListener(new FileUploadProgressListener(session, fileName));
        try {
            List<FileItem> fileItems = ((ServletFileUpload) fileUpload).parseRequest(request);
            return parseFileItems(fileItems, encoding);
        } catch (FileUploadBase.SizeLimitExceededException ex) {
            if (fileName != null){
                FILE_PROGRESS_MAP.put(fileName, FAIL_DOUBLE);
            }
            throw new MaxUploadSizeExceededException(fileUpload.getSizeMax(), ex);
        } catch (FileUploadException ex) {
            if (fileName != null){
                FILE_PROGRESS_MAP.put(fileName, FAIL_DOUBLE);
            }
            throw new MultipartException("Could not parse multipart servlet request", ex);
        }
    }

    public static void clear(String fileName){
        if (fileName == null){
            return;
        }
        FILE_PROGRESS_MAP.remove(fileName);
    }
}
